package com.example.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

/**
 * 认证资源配置.
 * @Author xcg
 * @Version 1.0
 */
@Configuration
@EnableResourceServer
public class ResourceConfig extends ResourceServerConfigurerAdapter {


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("admin").tokenStore(tokenStore()).stateless(true);
    }

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .authorizeRequests()
                .antMatchers("/oauth/**", "/oauth2/**", "/login/**", "logout/**","/websocket/**").permitAll()
                .antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated()
//                .and()
//                .formLogin()
//                .loginPage("/login") // 自定义登录表单
                //.defaultSuccessUrl("/home", true)  // 登录成功跳转的页面，第二个参数true表示每次登录成功都是跳转到home，如果false则表示跳转到登录之前访问的页面
                //.failureUrl("/login?error=true")
//                .failureHandler(authenticationFailureHandler())  // 失败跳转的页面（比如用户名/密码错误），这里还是跳转到login页面，只是给出错误提示
                .and().logout().permitAll()  // 登出 所有用户都可以访问
                .and().csrf().disable();
    }

    @Autowired
    private DataSource dataSource;


    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

//
//    public TokenStore tokenStore() {
//       return new InMemoryTokenStore();
//    }


}
